package mrpanyu.guitool.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;

@ToolModel(displayName = "JSR233脚本执行")
public class ScriptTool {

	@Parameter(displayName = "脚本引擎", type = ParameterType.SELECT, options = { "Groovy" }, order = 1)
	private String engine;

	@Parameter(displayName = "脚本", type = ParameterType.MULTILINE_TEXT, order = 2)
	private String script;

	@Action(displayName = "执行", order = 1)
	public void run(Tool tool) throws Exception {
		ScriptEngine se = new ScriptEngineManager().getEngineByName(engine);
		se.getContext().setWriter(new ToolWriter(tool, false));
		se.getContext().setErrorWriter(new ToolWriter(tool, true));
		Object returnValue = se.eval(script);
		if (returnValue != null) {
			tool.infoMessage("" + returnValue);
		}
	}

	@Action(displayName = "清空", order = 2)
	public void clear(Tool tool) {
		tool.clearMessages();
	}

}
